<?php
/**
 * Nguoi tao: nghiat
 * Ngay tao: 09/11/2010
 * Y nghia: Class thu ly HS
 */	
class web_userController extends  Zend_Controller_Action {	
	public function init(){	
        $tempDirApp = Zend_Registry::get('conDirApp');
		$this->_dirApp = $tempDirApp->toArray();
		$this->view->dirApp = $tempDirApp->toArray();
		if (!$this->_request->isXmlHttpRequest()){
			//Cau hinh cho Zend_layout
			Zend_Layout::startMvc(array(
					'layoutPath' => $this->_dirApp['layout'],
					'layout' => 'web'			    
					));	
			//Load ca thanh phan cau vao trang layout (index.phtml)
			$response = $this->getResponse();
			//Ky tu dac biet phan tach giua cac phan tu
			$this->view->delimitor 	= "!~~!";	
			//Load cau hinh thu muc trong file config.ini de lay ca hang so dung chung
			$tempConstPublic = Zend_Registry::get('ConstPublic');
			$this->_ConstPublic = $tempConstPublic->toArray();	
			$objlibrary = new Efy_Library();
			//Lay duong dan thu muc goc (path directory root)
			$this->view->baseUrl = $this->_request->getBaseUrl() . "/public/";	
			
			Zend_Loader::loadClass('mtl_modUser');
			$objConfig = new Efy_Init_Config();
			$objFunction = New Efy_Function_RecordFunctions();	
			$this->view->JSPublicConst = $objConfig->_setJavaScriptPublicVariable();		
			$arrAuthors = $objFunction->getAllObjectbyListCodeFull('','DM_TAC_GIA');
			$arrput = array();
			foreach ($arrAuthors as $key => $author) {
				if ($author['DISPLAY_HOME']) {
					array_push($arrput, $author);
				}
			}
			$this->view->arrAuthors = $arrput;
			//Tao doi tuong XML
			Zend_Loader::loadClass('Efy_Publib_Xml');		
			// Load tat ca cac file Js va Css
			$this->view->LoadAllFileJsCss = Efy_Publib_Library::_getAllFileJavaScriptCss('','efy-js','web/home.js,efyxml.js',',','js')
											.$objlibrary->_getAllFileJavaScriptCss('','efy-style','style_OnNet.css',',','css');	
			//Lay tra tri trong Cookie
			$sGetValueInCookie = $objlibrary->_getCookie("showHideMenu");
			
			//Neu chua ton tai thi khoi tao
			if ($sGetValueInCookie == "" || is_null($sGetValueInCookie) || !isset($sGetValueInCookie)){
				$objlibrary->_createCookie("showHideMenu",1);
				$objlibrary->_createCookie("ImageUrlPath",$this->_request->getBaseUrl() . "/public/images/close_left_menu.gif");
				//Mac dinh hien thi menu trai
				$this->view->hideDisplayMeneLeft = 1;// = 1 : hien thi menu
				//Hien thi anh dong menu trai
				$this->view->ShowHideimageUrlPath = $this->_request->getBaseUrl() . "/public/images/close_left_menu.gif";
			}else{//Da ton tai Cookie
				/*
				Lay gia tri trong Cookie, neu gia tri trong Cookie = 1 thi hien thi menu, truong hop = 0 thi an menu di
				*/
				if ($sGetValueInCookie != 0){
					$this->view->hideDisplayMeneLeft = 1;// = 1 : hien thi menu
				}else{
					$this->view->hideDisplayMeneLeft = "";// = "" : an menu
				}
				//Lay dia chi anh trong Cookie
				$this->view->ShowHideimageUrlPath = $objlibrary->_getCookie("ImageUrlPath");
			}
			$this->view->currentModulCode = "RECORD-NET";
			 $response->insert('header', $this->view->renderLayout('header_web.phtml','./application/views/scripts/'));
			$response->insert('left', $this->view->renderLayout('left_web.phtml','./application/views/scripts/'));
			$response->insert('right', $this->view->renderLayout('right_web.phtml','./application/views/scripts/'));
	        $response->insert('footer', $this->view->renderLayout('footer.phtml','./application/views/scripts/')); 			

		}
	}
	/**
	 * Idea : Phuong thuc hien thi danh sach
	 */
	public function indexAction(){			
		//Goi cac doi tuong		
		$md5_hash = md5(rand(0,999)); 
		$security_code = substr($md5_hash, 15, 9); 
		$_SESSION["security_code"] = $security_code;
		//main or support
	}
	/**
	 * Idea : changepass
	 */
	public function changepassAction(){			
		$objUser		= new mtl_modUser();
		$sesAccount = new Zend_Session_Namespace('Account');
		if(!isset($sesAccount->id)){
			$this->_redirect('/web/index/index/');
		}
		$sOldpass 		= 	$this->_request->getParam('txt_password_old',"");
		$sNewpass 		= 	$this->_request->getParam('txt_password_new',"");
		if(isset($sOldpass)& $sOldpass!=""){
			$sOldpass=md5($sOldpass);
			$login = $objUser->eCSNetCheckLogin($sesAccount->userName,$sOldpass);
			if(is_null($login) || sizeof($login)==0 ||!$login){?>
				<script language="JavaScript">
					alert('Mật khẩu không đúng');
				</script>				
			<?php }
			else {
				$changepass = $objUser->eCSNetUpdatePass($login['PK_NET_ID'],md5($sNewpass));
				$_SESSION['success']['act'] = 'changepass';
				$this->_redirect('web/user/success');
			}
		}
	}
	/**
	 * 
	 * Enter description here ...
	 */
	public function registerAction(){ //Cap nhat chuyen tiep HS
		$pUpdate = $this->_request->getParam('hdn_update','');
		//Goi doi tuong
		$objRecordFunction	     = new Efy_Function_RecordFunctions();	
		$objTax	  				 = new mtl_modUser();
		$objInitConfig 			 = new Efy_Init_Config();
		$ojbEfyLib				 = new Efy_Library();
		$sFullname 				 = 	$this->_request->getParam('txt_fullname',"");
		$sUsername 				 = 	$this->_request->getParam('txt_username',"");
		$sPassword 				 = 	$this->_request->getParam('txt_password',"");
		$sRePassword 			 = 	$this->_request->getParam('txt_repassword',"");
		$sEmail		 			 = 	$this->_request->getParam('txt_email',"");
		$sSocmnd 				 = 	$this->_request->getParam('txt_scmnd',"");
		$this->view->fullname	=$sFullname;
		$this->view->username	=$sUsername;
		$this->view->password	=$sPassword;
		$this->view->repassword	=$sRePassword;
		$this->view->email		=$sEmail;
		$this->view->socmnd		=$sSocmnd;
		if($pUpdate=='1'){
			//Cap nhat CSDL
			$arrParameter = array(	
						'PK_NET_ID'									=>	'',															
						'C_FULLNAME'								=>	$sFullname,
						'C_USERNAME'								=>	$sUsername,															
						'C_PASSWORD'								=>	md5($sPassword),
						'C_EMAIL'									=>	$sEmail,
						'C_ID_CARD'									=>	$sSocmnd,
						'C_CREATED_DATE'							=>	null,	 
						'C_XML_DATA'								=>	null							
						);
			$arrResult = $objTax->eCSNetUserUpdate($arrParameter);	//Goi model cap nhat vao CSDL

			if(is_null($arrResult['RET_ERROR'])||$arrResult['RET_ERROR']=='' ){
				$this->setLogin($arrResult);
				$_SESSION['success']['act'] == 'register';
				$this->_redirect('web/user/success/');
			}else{?>
				<script language="JavaScript">
					alert('<? echo $arrResult['RET_ERROR']?>');
				</script>
			<?php }
		}
	}
	/**
	 * 
	 * Enter description here ...
	 */
	public function getcaptchaAction(){
		Zend_Loader::loadClass('Efy_Captcha');
		$objConfig = new Efy_Init_Config();
		$sImgDir = $_SERVER['DOCUMENT_ROOT'].$objConfig->_setWebSitePath().'public/captcha/';
		$sImgUrl = $objConfig->_setWebSitePath().'public/captcha/';
		$captcha = new Efy_Captcha();
		$captcha->setImgDir($sImgDir);
		$captcha->setImgUrl($sImgUrl);
		$captcha->setFont($sImgDir.'League_Gothic-webfont.ttf');
		$captcha->setWordlen(6);
		$captcha->setFontSize(28);
		$captcha->setLineNoiseLevel(3);
		$captcha->setWidth(120);
		$captcha->setHeight(64);
		//$captcha->setGcFreq(5);
		$captcha->generate();
		Zend_Loader::loadClass('Zend_Session_Namespace');
		$captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_' . $captcha->getId());
		$captchaWord = $captchaSession->word;
		$_SESSION["security_code"] = $captchaWord;
		$this->view->captcha = $captcha;
	}
	public function checkcaptchaAction(){
		//Kiem tra captcha
		$captcha = $_REQUEST['v_input'];
		$arrCaptcha = array(	
							'id'	=>	$_SESSION["security_code"],															
							'input'	=>	$captcha							
							);
		$iCheck = $this->validateCaptcha($arrCaptcha);
		echo $iCheck;exit;
	}
	//validates captcha response
	private function validateCaptcha($captcha) {
		$captchaId = $captcha['id'];
		$captchaInput = $captcha['input'];
		//echo $captchaId,'-',$captchaInput;
		if( $captchaInput != $captchaId ){
			return 0;
		} else {
			return 1;
		}
	}
	/**
	 * Idea : Phuong thuc dang nhap
	 *
	 */
	public function loginAction(){
	    $objrecordfun 				= new Efy_Function_RecordFunctions();
		$objInitConfig 			 	= new Efy_Init_Config();
		$objXml					 	= new Efy_Publib_Xml();
        $objLibrary 				= new Efy_Library();
        $modelUser 			= new mtl_modUser();
		
		$objConfig  = new  Efy_Init_Config();
        $this->view->url = 'http://'.$_SERVER['HTTP_HOST'].$objConfig->_setWebSitePath();
		
		$sesAccount = new Zend_Session_Namespace('Account');
		if(isset($sesAccount->id)){
			$this->_redirect('/web/index/index/');
		}

		$username = $this->_request->getParam('username','');
		$password = $this->_request->getParam('password','');
		$remember = $this->_request->getParam('remember','');		
		$commit = $this->_request->getParam('commit','');	
		if ($this->_request->isPost()) {
			$objLibrary->_createCookie("remember",$remember);
			$arrCheckLogin = $modelUser->eCSNetCheckLogin($username,md5($password));
			if(sizeof($arrCheckLogin) > 0){
				if ($remember) {
					Efy_Library::_createCookie("TTDNCDhas",$arrCheckLogin['PK_NET_ID']);
					$objLibrary->_createCookie("username",$username);
	    			$objLibrary->_createCookie("password",$password);
				}
				 // Dang nhap thanh cong
				$this->setLogin($arrCheckLogin);
				$this->_redirect('/web/index/index/');
			}else{?>
				<script language="JavaScript">
						alert('Tên đăng nhập hoặc mật khẩu không chính xác!');
				</script>
			<?php 
			}
		} else{
			$remember = $objLibrary->_getCookie("remember");
	        if($remember){
			   $username = $objLibrary->_getCookie("username");
			   $password = $objLibrary->_getCookie("password");
			}else{
			  $remember = 0;
			}
		}
		$this->view->username = $username;
		$this->view->password = $password;
	}
	private function setLogin($arrInfo) {
		$sesAccount = new Zend_Session_Namespace('Account');
		$sesAccount->userName 	= $arrInfo['C_USERNAME'];
		$sesAccount->id 		= $arrInfo['PK_NET_ID'];
		$sesAccount->fullName 	= $arrInfo['C_FULLNAME'];
		$sesAccount->email 		= $arrInfo['C_EMAIL'];
		$sesAccount->role 		= $arrInfo['C_ROLE'];
		$sesAccount->status 	= $arrInfo['C_STATUS'];
	}
	/**
	*
	*
	**/
	public function logoutAction(){
		Zend_Session:: namespaceUnset('Account');
		Zend_Session:: namespaceUnset('error');
		Zend_Session:: namespaceUnset('success');
		Efy_Library::_delCookie("TTDNCDhas");	
		$this->_redirect('/web/index/index/');
	}
	public function randomPassword(){
	    $alphabet = "abcdefghjkmnpqrstuwxyzABCDEFGHKMNPQRSTUWXYZ123456789";
	    $pass = array();
	    $alphaLength = strlen($alphabet) - 1;
	    for ($i = 0; $i < 8; $i++) {
	        $n = rand(0, $alphaLength);
	        $pass[] = $alphabet[$n];
	    }
	    return implode($pass);
	}
	public function lostpassAction() {
		$sesAccount = new Zend_Session_Namespace('Account');
		if(isset($sesAccount->id)){
			$this->_redirect('web/index/index/');
		}
		$objInitConfig 	= new Efy_Init_Config();
		$objLib	     	= new Efy_Library();
		$arrInput= $this->_request-> getParams();
		$actionUpdate = $arrInput['hdnaction'];
		$username = $arrInput['txt_username'];
		if ($actionUpdate == 'lostpass'){
			$objModel = new mtl_modUser();
			$arrInfo = $objModel->eCSNetCheckUserName($username);
			if ($arrInfo['PK_NET_ID'] != ''){
				$sNewpass = $this->randomPassword();
				$changepass = $objModel->eCSNetUpdatePass($arrInfo['PK_NET_ID'],md5($sNewpass));
				//Update lai mat khau ngau nhien cho cong dan						
				$arrInfo['C_EMAIL'] = 'dvtruongbk@gmail.com';
				$objLib->sendEmail(array(
						'template'=>'lostpass.htm'
						,'email'=>$arrInfo['C_EMAIL']
						,'name'=>$arrInfo['C_NAME']
						,'subject'=>'Thay đổi mật khẩu, ngày '.date('d/m/Y H:i')
						,'body_data'=>array(
								'#username#'=>$arrInfo['C_USERNAME']
								,'#password#'=>$sNewpass
						)
				));
				$_SESSION['success']['act'] == 'confirmchangepass';
				$this->_redirect('web/user/success/');
			}else{				?>
				<script language="JavaScript">
						alert('Tên đăng nhập không chính xác!');
				</script>
			<?php 
			}
		}		
	}

	public function successAction(){
		
	}
}?>
